#include "ProTocol.hpp"
#include "Socket.hpp"
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>

// void *pthreadRountine(void *args)
// {
//         // 发送 和 接受
//         conn->Send(request_string);
//         std::string response_string; // 接受的响应数据 含报头
//         while(true)
//         {
//             if(!conn->Recv(&response_string, 1024))
//                 break;

//             std::string response;
//             if(!Protocol::Decode(response_string, &response))
//                 continue;

//             // 填充响应对象
//             std::shared_ptr<Protocol::Response> resp = factory->BuildResponse();
//             resp->Deserialize(response);

//             std::cout << resp->GetResult() << "[" << resp->GetCode() << "]" << std::endl;
//         }
// }

// ./server serverip serverport
int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        std::cout << "Usage: " << argv[0] << " serverip serverport" << std::endl;
        return 0;
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 创建套接字
    Net_Work::Socket *conn = new Net_Work::TcpSocket();
    if(!conn->BuildConnectSocketMethod(serverip, serverport))
    {
        std::cout << "connect " <<serverip << ":" << serverport << "false" << std::endl;
        return 0;
    }
    std::cout << "connect " <<serverip << ":" << serverport << "success" << std::endl;

    // 构建请求对象
    std::unique_ptr<Protocol::Factory> factory = std::make_unique<Protocol::Factory>();

    srand(time(nullptr) ^ getpid());
    const std::string opers = "+-*/%";
    while(true)
    {
        // 填充请求对象
        int x = rand() % 1000;
        int y = rand() % 1000;
        char oper = opers[rand() % opers.size()];
        std::shared_ptr<Protocol::Request> req = std::make_shared<Protocol::Request>(x, y, oper);
        //req->Debug();

        // 序列化 和 填充自描述报头
        std::string request_string;
        req->Serialize(&request_string);
        std::cout << request_string << std::endl;

        request_string = Protocol::Encode(request_string);

        // 发送 和 接受
        conn->Send(request_string);
        std::string response_string; // 接受的响应数据 含报头
        //while(true)
        //{
            if(!conn->Recv(&response_string, 1024))
                break;

            std::string response;
            if(!Protocol::Decode(response_string, &response))
                continue;

            // 填充响应对象
            std::shared_ptr<Protocol::Response> resp = factory->BuildResponse();
            resp->Deserialize(response);

            std::cout << resp->GetResult() << "[" << resp->GetCode() << "]" << std::endl;
        //}

        sleep(1);
    }

    return 0;
}